package figure8.Network;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

import figure8.Network.Message.Type;
import figure8.events.NetworkEventListener;
import figure8.events.NetworkEventSource;

public class NetworkLayer implements Runnable, NetworkConnection {
	protected String address = "";
	protected int port;
	
	protected boolean auth;
	
	protected NetworkConnection connection;
	
	protected Map<Integer, String> users;
	
	public NetworkLayer(int port) {
		this.port = port;
		this.connection = null;
		this.users = new HashMap<Integer, String>();
	}
	
	public void connect(String address) throws UnknownHostException, IOException {
		Socket socket = new Socket(address, port);
		
		this.auth = false;
		this.connection = new Client(socket, false, 0);
	}
	
	public void host() {
		this.auth = true;
		this.connection = new Server(port);
		
		this.users.put(0, "Server");
	}
	
	public void disconnect(String reason) {
		Message message;
		
		if (auth) {
			message = new Message(Type.SERVER_SHUTDOWN, reason);
		} else {
			message = new Message(Type.CLIENT_LEFT, reason);
		}
		
		this.connection.send(message);
		this.connection.disconnect();
	}
	
	public void send(Message message) {
		this.connection.send(message);
	}
	
	public void send(Message message, Client exclude) {
		this.connection.send(message, exclude);
	}
	
	public void run() {
		this.connection.run();
	}
	
	@Override
	public void addNetworkEventListener(NetworkEventListener listener) {
		this.connection.addNetworkEventListener(listener);
	}

	@Override
	public void removeNetworkEventListener(NetworkEventListener listener) {
		this.connection.removeNetworkEventListener(listener);
	}

	@Override
	public void disconnect() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean isHost() {
		return this.auth;
	}
}
